USE [QLDL]
GO

/****** Object:  StoredProcedure [dbo].[sp_ThemChiTietPXH]    Script Date: 01/03/2011 15:28:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[sp_ThemChiTietPXH]
	@MaPhieuXuat nvarchar(10), @TenMatHang ntext, @SoLuong int
as
begin
	if not exists(select * from MATHANG where TenMatHang like @TenMatHang)
		return 1
		
	declare @MaCT nvarchar(10)
	select @MaCT = MaCT from CT_PHIEUXUATHANG order by (CAST(RIGHT(MaCT, LEN(MaCT) - 5) as int)) asc
	if (@MaCT is not null)
		set @MaCT = N'CTPXH' + CAST((CAST(RIGHT(@MaCT, LEN(@MaCT) - 5) as int) + 1) as nvarchar)
	else
		set @MaCT = N'CTPXH1'
	
	declare @MaMatHang nvarchar(10)
	declare @DonGia money
	select @MaMatHang = MaMatHang, @DonGia = DonGia from MATHANG where TenMatHang like @TenMatHang 	
	declare @ThanhTien money
	set @ThanhTien = @SoLuong * @DonGia
		
	insert into CT_PHIEUXUATHANG(MaCT, MaPhieuXuat, MaMatHang, SoLuong, DonGiaXuat, ThanhTien)
						values(@MaCT, @MaPhieuXuat, @MaMatHang, @SoLuong, @DonGia, @ThanhTien)
	
	update PHIEUXUATHANG set TongTien = TongTien + @ThanhTien where MaPhieuXuat = @MaPhieuXuat
	
	declare @MaDaiLy nvarchar(10)
	select @MaDaiLy = MaDaiLy from PHIEUXUATHANG where MaPhieuXuat = @MaPhieuXuat
	update DAILY set TienNo = TienNo + @ThanhTien where MaDaiLy = @MaDaiLy
	
	return 0
end
GO


